<?php
require_once(_PS_MODULE_DIR_.'zcustomerpoint/classes/ZcustomerPointObject.php');
class MyAccountController extends FrontController
{
	public $auth = true;
	public $php_self = 'my-account.php';
	public $authRedirection = 'my-account.php';
	public $ssl = true;
	
	public function preProcess()
	{
		parent::preProcess();
		
		$customer = new Customer((int)(self::$cookie->id_customer));

		if (sizeof($_POST))
		{
			$exclusion = array('secure_key', 
									'old_passwd',
									'username',
									'code',
									'parent',
									'passwd', 
									'active', 
									'date_add', 
									'date_upd', 
									'last_passwd_gen', 
									'newsletter_date_add', 
									'id_default_group', 
									'ip_registration_newsletter',
									'note',
									'is_guest');
			
			$fields = $customer->getFields();
			foreach ($fields AS $key => $value)
				if (!in_array($key, $exclusion))
					$customer->{$key} = key_exists($key, $_POST) ? trim($_POST[$key]) : 0;
		}

		if (isset($_POST['years']) AND isset($_POST['months']) AND isset($_POST['days']))
			$customer->birthday = (int)($_POST['years']).'-'.(int)($_POST['months']).'-'.(int)($_POST['days']);
			
		if (Tools::isSubmit('SubmitCodePoints'))
		{
			$receipt_point = $_POST['receipt_point'];
			$arrCode = $this->_getListCodePoint();
			$time_now = date('Y-m-d H:i:s');
			foreach ($arrCode AS $key=>$code){
				if ($receipt_point==$code['code'] AND $code['points'] > 0){
					// check time
					if ( $code['uses_per_coupon'] > 0  OR 
					($code['to_time'] == '0000-00-00 00:00:00' AND  strtotime($time_now) >= strtotime($code['start_time'])) OR 
					(strtotime($time_now) >= strtotime($code['start_time']) AND strtotime($time_now) <= strtotime($code['to_time']))){
			 			
						if (!$this->_checkCustomerCodePoint((int)(self::$cookie->id_customer), (int)$code['id_zcode_point']))
						{
							if (ZcustomerPointObject::_updatePointToCustomer((int)(self::$cookie->id_customer), (int)$code['points']))
							{
								$field = array('id_zcode_point' => (int)$code['id_zcode_point'], 
												'id_customer' => (int)(self::$cookie->id_customer));
								Db::getInstance()->AutoExecute(_DB_PREFIX_.'zcode_point_customer', $field, 'INSERT');
								Db::getInstance()->ExecuteS('UPDATE `'._DB_PREFIX_.'zcode_point` SET `uses_per_coupon` = `uses_per_coupon`-1 WHERE `id_zcode_point` = '.(int)$code['id_zcode_point']);
								self::$smarty->assign(array('confAddPoint'=> 1, 'cpoints'=>$code['points'] ));
								break;
							}
						}else {
							self::$smarty->assign(array('confAddPoint'=> 3,'codepoints'=> $receipt_point));
							break;
						}
			 		} else {
			 			self::$smarty->assign(array('confAddPoint'=> 4,'codepoints'=> $receipt_point));
						break;
			 		}
				}else{
					self::$smarty->assign(array('confAddPoint'=> 2,'codepoints'=> $receipt_point));
				}
			}
		}
		
		if (Tools::isSubmit('submitIdentity'))
		{
			
			if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) AND
			!(Tools::getValue('months') == '' AND Tools::getValue('days') == '' AND Tools::getValue('years') == ''))
				$this->errors[] = Tools::displayError('Invalid date of birth');
			else
			{
				$customer->birthday = (empty($_POST['years']) ? '' : (int)($_POST['years']).'-'.(int)($_POST['months']).'-'.(int)($_POST['days']));

				$_POST['old_passwd'] = trim($_POST['old_passwd']);
				if (empty($_POST['old_passwd']) OR (Tools::encrypt($_POST['old_passwd']) != self::$cookie->passwd))
					$this->errors[] = Tools::displayError('Your password is incorrect.');
				else
				{
					$this->errors = $customer->validateControler();
				}
				if (!sizeof($this->errors))
				{
					$customer->name = Tools::ucfirst(Tools::strtolower($customer->name));
					if (Tools::getValue('passwd'))
						self::$cookie->passwd = $customer->passwd;
						
					if ($customer->update())
					{
						self::$cookie->fullname = $customer->name;
						self::$smarty->assign('confirmation', 1);
					}
					else
						$this->errors[] = Tools::displayError('Cannot update information');
				}
			}
		}
		else{
			$_POST = array_map('stripslashes', $customer->getFields());
		}
		
		if ($customer->birthday)
			$birthday = explode('-', $customer->birthday);
		else
			$birthday = array('-', '-', '-');
			
		// convert months to vietnames	
		$months = Tools::dateMonths();
		$i=1;
		foreach ($months AS $value){
			switch($value)
				{
					case "January":   $months[$i] = "Tháng 1";    break;
					case "February":  $months[$i] = "Tháng 2";   break;
					case "March":     $months[$i] = "Tháng 3";     break;
					case "April":     $months[$i] = "Tháng 4";     break;
					case "May":       $months[$i] = "Tháng 5";       break;
					case "June":      $months[$i] = "Tháng 6";      break;
					case "July":      $months[$i] = "Tháng 7";      break;
					case "August":    $months[$i] = "Tháng 8";    break;
					case "September": $months[$i] = "Tháng 9"; 		break;
					case "October":   $months[$i] = "Tháng 10";   break;
					case "November":  $months[$i] = "Tháng 11";  break;
					case "December":  $months[$i] = "Tháng 12";  break;
				}
			$i++;
		}
		$city = "An Giang,Bà Rịa-Vũng Tàu,Bạc Liêu,Bắc Kạn,Bắc Giang,Bắc Ninh,Bến Tre,Bình Dương,Bình Định,Bình Phước,Bình Thuận,Cà Mau,Cao Bằng,Cần Thơ,Đà Nẵng,Đắk Lắk,Đắk Nông,Điện Biên,Đồng Nai,Đồng Tháp,Gia Lai,Hà Giang,Hà Nam,Hà Nội,Hà Tĩnh,Hải Dương,Hải Phòng,Hòa Bình,Hồ Chí Minh,Hậu Giang,Hưng Yên,Khánh Hòa,Kiên Giang,Kon Tum,Lai Châu,Lào Cai,Lạng Sơn,Lâm Đồng,Long An,Nam Định,Nghệ An,Ninh Bình,Ninh Thuận,Phú Thọ,Phú Yên,Quảng Bình,Quảng Nam,Quảng Ngãi,Quảng Ninh,Quảng Trị,Sóc Trăng,Sơn La,Tây Ninh,Thái Bình,Thái Nguyên,Thanh Hóa,Thừa Thiên Huế,Tiền Giang,Trà Vinh,Tuyên Quang,Vĩnh Long,Vĩnh Phúc,Yên Bái";
		$arrCity = explode(',',$city);
		
		$customerPoint = Db::getInstance()->getRow('SELECT * FROM '._DB_PREFIX_.'zcustomerpoint_accounts 
														WHERE id_customer = '.(int)(self::$cookie->id_customer));

		/* Generate years, months and days */
		self::$smarty->assign(array(
			'points' => $customerPoint['points_current'],
			'city' => $arrCity,
			'customer' => self::$cookie->passwd,
			'years' => Tools::dateYears(),
			'sl_year' => $birthday[0],
			'months' => $months,
			'sl_month' => $birthday[1],
			'days' => Tools::dateDays(),
			'sl_day' => $birthday[2],
			'errors' => $this->errors
		));
		
		self::$smarty->assign('newsletter', (int)Module::getInstanceByName('blocknewsletter')->active);
	}
	
	public function setMedia()
	{
		parent::setMedia();
		Tools::addCSS(_THEME_CSS_DIR_.'identity.css');
		Tools::addJS(_THEME_JS_DIR_.'validate.js');
	}
	
	public function displayContent()
	{
		parent::displayContent();
		self::$smarty->display(_PS_THEME_DIR_.'my-account.tpl');
	}
	/**
	 * 
	 * get all code to table zcode_point
	 */
	public function _getListCodePoint(){
		$result = Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'zcode_point` 
														WHERE  `active` = 1');
		return $result;
	}
	
	public function _checkCustomerCodePoint($id_customer,$id_zcode_point){
		$result = Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'zcode_point_customer` 
														WHERE `id_zcode_point` = '.$id_zcode_point.' AND `id_customer`='.$id_customer);
		
		return $result;
	}
}


